class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int n = matrix.size();
        int m = matrix[0].size();

        int l=0,r=m-1;
        int t=0,b=n-1;
        vector<int> ret;
        while(1)
        {
            //left to right
            for(int i=l;i<=r;i++)
                ret.push_back(matrix[t][i]);
            t++;
            if(t>b)
                break;
            //top to bottom
            for(int i=t;i<=b;i++)
            {
                ret.push_back(matrix[i][r]);
            }
            if(--r<l)
                break;
            //right to left
            for(int i=r;i>=l;i--)
            {
                ret.push_back(matrix[b][i]);
            }
            if(--b<t)
                break;
            //bottom to top
            for(int i=b;i>=t;i--)
            {
                ret.push_back(matrix[i][l]);
            }
            if(++l>r)
                break;

        }
        return ret;
    }
};
